package com.sangmo.boot.auth.core;


import com.sangmo.boot.auth.core.errors.ErrorMessages;
import com.sangmo.boot.auth.core.model.Client;
import com.sangmo.boot.auth.core.repo.ClientRepo;
import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class ClientService extends BaseViewService<Client> {

	@Autowired
	private ClientRepo repo;

	@Override
	public ClientRepo getRepo() {
		return repo;
	}

	public Client findByName(String name) {
		return this.repo.findOneByName(name);
	}

	public Client validateClient(String clientId, String secret) {
		Client client = this.find(clientId);
		if(client == null) {
			throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_NAMENOTEXISTS);
		}

		if(!client.getSecret().equals(secret)) {
			throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_SECRET_WRONG);
		}

		if (!Client.States.ENABLED.equals(client.getState())) {
			throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_DISABLED);
		}
		return client;
	}
}
